package com.wangxiaonan.berry.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wangxiaonan.berry.entity.Barn;
import com.wangxiaonan.berry.repository.BarnRepository;
import com.wangxiaonan.berry.service.BarnService;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Optional;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

@Service
@Transactional
public class BarnServiceImpl implements BarnService {

    private static final Logger logger = LoggerFactory.getLogger(BarnServiceImpl.class);

    @Resource
    private BarnRepository barnRepository;

    @Override
    public Barn findById(int id) {
        Optional<Barn> optional = barnRepository.findById(id);
        return optional.orElse(null);
    }

    @Override
    public List<Barn> findList(Barn queryBarn) {
        if (queryBarn == null) {
            queryBarn = new Barn();
        }
        Example<Barn> example = Example.of(queryBarn);
        return barnRepository.findAll(example);
    }

    @Override
    public Barn storeBarn(Barn barn) {
        Assert.notNull(barn, "save entity is illegal!");
        return barnRepository.save(barn);
    }

    @Override
    public List<String> summariseTitles(String type) {
        Barn barn;
        if (StringUtils.isEmpty(type)) {
            barn = barnRepository.findFirstByCargoNotNullOrderByIdDesc();
        } else {
            barn = barnRepository.findFirstByCargoNotNullAndTypeOrderByIdDesc(type);
        }

        if (barn == null) {
            return new ArrayList<>();
        }
        String cargo = barn.getCargo();
        JSONObject data = JSONObject.parseObject(cargo);
        if (data == null || data.isEmpty()) {
            return new ArrayList<>();
        }

        List<String> titles = new ArrayList<>();
        for (Entry<String, Object> title : data.entrySet()) {
            titles.add(title.getKey());
        }
        return titles;
    }

    @Override
    public String[][] collectCellValue(List<String> keys, int startRowNum, String type, Pageable pageable) {
        if (CollectionUtils.isEmpty(keys)) {
            return new String[startRowNum][0];
        }

        Barn barn = new Barn();
        if (!StringUtils.isEmpty(type)) {
            barn.setType(type);
        }

        Example<Barn> queryExample = Example.of(barn);
        Page<Barn> page = barnRepository.findAll(queryExample, pageable);
        List<Barn> cargo = page.getContent();

        int count = cargo.size() + startRowNum;
        int cellCount = keys.size();
        String[][] content = new String[count][cellCount];

        // 赋值
        for (int i = 0; i < cargo.size(); ++i) {

            JSONObject c;
            try {
                c = JSONObject.parseObject(cargo.get(i).getCargo());
            } catch (Exception e) {
                logger.error("数据无效 [{}]", cargo.get(i).getCargo(), e);
                continue;
            }

            if (c == null || c.isEmpty()) {
                continue;
            }
            for (int j = 0; j < cellCount; ++j) {
                content[i + startRowNum][j] = c.getString(keys.get(j));
            }
        }

        return content;
    }
}
